package com.chat.dao;

import com.chat.entity.User;
import com.chat.util.HibernateUtil;
import com.chat.util.RedisUtil;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.Jedis;

import javax.transaction.Transactional;

@Repository
public class UserDaoImpl implements UserDao{
    @Transactional
    public void add(User user) {
        Session session=HibernateUtil.getCurrentSession();
        session.save(user);
    }

    public void update(User user) {
        Session session=HibernateUtil.getCurrentSession();
        session.update(user);
    }

    public User getUser(String id) {
        Session session=HibernateUtil.getCurrentSession();
        return session.get(User.class,new Short(id));
    }

    public User getUserByEmail(String email) {
        Session session=HibernateUtil.getCurrentSession();
        Query<User> query=session.createQuery(
                "from User where email=?",User.class);
        query.setParameter(0,email);

        return query.uniqueResult();
    }

    public User getBriefUserByEmail(String email) {
        Session session=HibernateUtil.getCurrentSession();
        Query<User> query=session.createQuery(
                "select new User (id,email,signature,integral,status,img,username)" +
                        "from User where email=:email",User.class);
        query.setParameter("email",email);

        return query.uniqueResult();
    }

    @Override
    public String getCertificate(String email) {
        Jedis jedis=RedisUtil.getJedis();
        String certificate=jedis.get("chat:user:certificate:"+email);

        if(certificate==null){
            User user=getUserByEmail(email);
            certificate=user.getCertificate();
            if(certificate!=null){
                jedis.setex("chat:user:certificate:"+email,900,certificate);
            }
        }

        return certificate;
    }

    @Override
    public boolean isAlive(String email) {
        Jedis jedis=RedisUtil.getJedis();
        String str=jedis.get("chat:user:isAlive:"+email);

        return str!=null;
    }

    @Override
    public void setUserAlive(String email) {
        Jedis jedis=RedisUtil.getJedis();
        jedis.setex("chat:user:isAlive:"+email,1000,"1");
    }

    @Override
    public void clear(String email) {
        Jedis jedis=RedisUtil.getJedis();
        jedis.del("chat:user:isAlive:"+email);
        jedis.del("chat:user:certificate:"+email);
    }
}
